﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Collections;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Sunny.UI;
using CoreShop.Model;
using CoreShop.Library;
using SqlSugar.Extensions;
using Yitter.IdGenerator;
using Org.BouncyCastle.Asn1;
using CoreShop.Services;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using Sunny.UI.Win32;
using CoreShop.App.Units.Interface;
using static CoreShop.Model.FromBody.DataResultModel;
using static CoreShop.Services.PosRemoteServices;
using System.Threading.Tasks;
using MySqlX.XDevAPI.Common;
using Loading;
using CoreShop.Model.ViewModels;

namespace CoreShop.App
{
    public partial class frmMemberPay : UIForm
    {
        private VipPayParaDto vipPayPara = null;
        private corecmsuser member = null;
        private corecmsfoodorderpayment orderpayment = null;
        private corecmsfoodorderingmaster orderingMaster = null;
        private corecmsuserbalance balance = new corecmsuserbalance();
        OpaqueCommand cmd = new OpaqueCommand();
        private int paySendState = (int)PaySendType.payStop;

        private enum PaySendType
        {
            [Description("支付提交中")]
            payRunning = 0,
            [Description("支付待提交")]
            payStop = 1
        }

        public frmMemberPay(corecmsfoodorderingmaster _orderingMaster,corecmsfoodorderpayment _orderpayment, corecmsuser _member,VipPayParaDto _vipPayPara)
        {
            InitializeComponent();
            vipPayPara = _vipPayPara;
            member = _member;
            orderpayment = _orderpayment;
            orderingMaster = _orderingMaster;
            CreatePaymentInfo();
        }

        public void CreatePaymentInfo()
        {
            balance.id = CommFunc.GetCorpNextId(AppConstVars.sysUser.corpId, YitIdHelper.NextId());
            //balance.orderId = YitIdHelper.NextId().ToString();
            balance.orderId = orderpayment.orderNo;
            balance.userId = member.id;
            balance.type = (int)GlobalEnumVars.UserBalanceTypes.Consume;
            balance.direction = -1;
            balance.storeId = AppConstVars.sysUser.storeId;
            balance.money = orderpayment.payAmount;
            balance.giftAmount = 0;
            balance.balance = member.balance - orderpayment.payAmount;
            balance.giftBalance = member.giftBalance.ObjToDecimal();
            balance.sourceId = 0;
            balance.memo = "";
            balance.createTime = DateTime.Now;
            balance.corpId = AppConstVars.sysUser.corpId;
            balance.cardItemId = 0;
            balance.quantity = 0;
            balance.balanceQuantity = 0;
            balance.sysUserId = AppConstVars.sysUser.id;
            balance.paymentId = orderpayment.paymentId;
            balance.paymentCode = orderingMaster.orderNo;
            balance.payStatus = (int)GlobalEnumVars.OrderPayStatus.UnPay;
            balance.status = (int)GlobalEnumVars.BalanceStatus.UnCheck;
            new corecmsuserbalanceServices().InsertAsync(balance);
            long receivableAmount = long.Parse((balance.money * 100).ToString("f0"));
            vipPayPara.vipId = member.id;
            vipPayPara.amount = receivableAmount;
            vipPayPara.businessType = PAYTYPE.BALANCE;
            vipPayPara.mchNo = balance.orderId;
            vipPayPara.branchId = AppConstVars.sysStore.branchId;
        }

        /// <summary>
        /// 会员支付
        /// </summary>
        public async Task<DataBoolResult> SetPaymentMember()
        {
            DataBoolResult result = new DataBoolResult();
            result.msg = "消费数据保存失败。";
            var payRs = await MemberApiUtil.SendVipPay(vipPayPara);
            result.code = payRs.code;
            result.msg = payRs.msg;
            if (payRs.code == 200)
            {                
                member.balance = balance.balance;
                member.giftBalance = balance.giftBalance;
                new corecmsuserServices().UpdateAsync(member);
                balance.payStatus = (int)GlobalEnumVars.OrderPayStatus.IsPay;
                balance.status = (int)GlobalEnumVars.BalanceStatus.IsCheck;
                balance.paymentTime = DateTime.Now;
                await new corecmsuserbalanceServices().InsertOrUpdateAsync(balance);
                orderpayment.paymentCode = balance.id.ToString();
                var payRsData = JsonConvert.DeserializeObject<VipPayResultDto>(payRs.data.ToString());
                orderpayment.payNo = payRsData.payNo;
                orderpayment.mchNo = payRsData.mchNo;
                orderingMaster.userOldBalance = payRsData.beforeAmount;
                orderingMaster.userNewBalance = payRsData.afterAmount;
                result.result = true;
            }
            return result;
        }

        private void SetMemberInfo()
        {
            this.Invoke(new Action(() =>
            {
                userName.Text = member.userName;
                mobile.Text = member.mobile;
                lbl_balance.Text = member.balance.ToString("#0.0#");
                lblGiftAmount.Text = CommFunc.ConvertToDecimal(member.giftBalance).ToString("#0.0#");
                lblPaymount.Text = orderpayment.payAmount.ToString("#0.0#");
            }));
        }

        private async void btn_Close_ClickAsync(object sender, EventArgs e)
        {
            if (paySendState == (int)PaySendType.payRunning)
            {
                if (!ShowAskDialog("支付进行中，确认要中断并退出吗？")) return;
                UIMessageBox.Show("您已中断支付，请在后台查看是否扣款成功，如已扣款，请补充值处理。");
                balance.payStatus = (int)GlobalEnumVars.OrderPayStatus.Cancel;
                balance.status = (int)GlobalEnumVars.BalanceStatus.UnCheck;
                balance.memo = "在支付提交中进行取消操作。";
                balance.paymentTime = DateTime.Now;
                await new corecmsuserbalanceServices().InsertOrUpdateAsync(balance);
                new corecmsprinttasklogServices().Insert($"会员支付在支付中手动取消支付，订单号[{orderpayment.orderNo}],支付单号[{orderpayment.paymentCode}]");
            }
            else 
                new corecmsprinttasklogServices().Insert($"会员支付手动取消支付，订单号[{orderpayment.orderNo}],支付单号[{orderpayment.paymentCode}]");
            this.DialogResult = DialogResult.Cancel;
        }
        
        private void frmMemberPay_Load(object sender, EventArgs e)
        {
            
        }

        private async void btnSendPayMore_Click(object sender, EventArgs e)
        {
            try
            {
                paySendState = (int)PaySendType.payRunning;
                cmd.ShowOpaqueLayer(pnl_Form, 125, true);
                var result = await SetPaymentMember();
                paySendState = (int)PaySendType.payStop;
                if (!result.result)
                {                    
                    btnSendPayMore.Text = "重新提交(F5)";
                    lblMessage.Text = "支付错误，请选择重新提交或其它操作。";
                    UIMessageBox.Show(result.msg, "支付出错:", UIStyle.Green, UIMessageBoxButtons.OK);
                    if (result.code == 1) this.DialogResult = DialogResult.Abort;
                }                    
                else
                {
                    balance.payStatus = (int)GlobalEnumVars.OrderPayStatus.IsPay;
                    balance.status = (int)GlobalEnumVars.BalanceStatus.IsCheck;
                    balance.paymentTime = DateTime.Now;
                    balance.memo = "会员支付成功。";
                    await new corecmsuserbalanceServices().InsertOrUpdateAsync(balance);
                    this.DialogResult = DialogResult.OK;
                }                   
            }
            catch (Exception ex) { }
            finally 
            {
                paySendState = (int)PaySendType.payStop;
                cmd.HideOpaqueLayer(); 
            }
        }

        private void frmMemberPay_Shown(object sender, EventArgs e)
        {
            if (AppConstVars.systemsetup.paraPartialModel.checkMemberPay) btnConfirmPay.Visible = true;
            SetMemberInfo();
            btnSendPayMore_Click(null,null);
        }

        private async void btnConfirmPay_ClickAsync(object sender, EventArgs e)
        {
            if (!ShowAskDialog("支付未完成，确定要返回并确认扣款成功吗？")) return;
            balance.payStatus = (int)GlobalEnumVars.OrderPayStatus.IsPay;
            balance.status = (int)GlobalEnumVars.BalanceStatus.IsCheck;
            balance.paymentTime = DateTime.Now;
            if (paySendState == (int)PaySendType.payRunning)                   
                balance.memo = "在支付提交中进行确认操作。";              
            else
                balance.memo = "支付失败后进行确认操作。";
            await new corecmsuserbalanceServices().InsertOrUpdateAsync(balance);
            orderpayment.outcomeType = (int)GlobalEnumVars.PayOutcomeType.Unknown;
            new corecmsprinttasklogServices().Insert($"会员支付手动确认，订单号[{orderpayment.orderNo}],支付单号[{orderpayment.paymentCode}]");
            this.DialogResult = DialogResult.OK;
        }

        private void frmMemberPay_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 27) btn_Close_ClickAsync(null, null);
            if ((e.KeyValue == 117) && (btnConfirmPay.Visible))
                btnConfirmPay_ClickAsync(null, null);
            if ((e.KeyValue == 116) && (paySendState == (int)PaySendType.payStop))
                btnSendPayMore_Click(null,null);
        }
    }
}
